from conf.config import redis_config
from conf.sys_conf import RedisInitKeyConfig
from core.exception.errors import ErrorException
from core.redis import redis_client
from schemas.common_schema import CacheInfoModel
from services.base_service import BaseService


class CacheService(BaseService):

    @classmethod
    async def get_cache_monitor_cache_name_services(cls):
        if not redis_config.OPEN_REDIS:
            raise ErrorException(msg="未启用Redis")

        name_list = []
        for key_config in RedisInitKeyConfig:
            name_list.append(
                CacheInfoModel(
                    cacheKey='',
                    cacheName=key_config.key,
                    cacheValue='',
                    remark=key_config.remark,
                )
            )
        return name_list

    @classmethod
    async def clear_cache_monitor_cache_name_services(cls, cache_name: str):
        """
        清除缓存名称对应所有键值service

        :param cache_name: 缓存名称
        :return: 操作缓存响应信息
        """
        cache_keys = await redis_client.keys(f'{cache_name}*')
        if cache_keys:
            await redis_client.delete(*cache_keys)

    @classmethod
    async def get_cache_monitor_cache_key_services(cls, cache_name: str):
        """
        获取缓存键名列表信息service

        :param cache_name: 缓存名称
        :return: 缓存键名列表信息
        """
        cache_keys = await redis_client.keys(f'{cache_name}*')
        cache_key_list = [key.split(':', 1)[1] for key in cache_keys if key.startswith(f'{cache_name}:')]
        return cache_key_list

    @classmethod
    async def get_cache_monitor_cache_value_services(cls, cache_name: str, cache_key: str):
        """
        获取缓存内容信息service
        :param cache_name: 缓存名称
        :param cache_key: 缓存键名
        :return: 缓存内容信息
        """
        cache_value = await redis_client.get(f'{cache_name}:{cache_key}')
        return CacheInfoModel(cacheKey=cache_key, cacheName=cache_name, cacheValue=cache_value, remark='')

    @classmethod
    async def clear_cache_monitor_cache_key_services(cls, cache_key: str):
        """
        清除缓存名称对应所有键值service
        :param cache_key: 缓存键名
        :return: 操作缓存响应信息
        """
        cache_keys = await redis_client.keys(f'*{cache_key}')
        if cache_keys:
            await redis_client.delete(*cache_keys)

